package com.maodou.android.utils

import android.content.Context
import android.content.pm.PackageManager
import android.os.Environment
import com.maodou.core.utils.Logger
import com.maodou.v2ray.util.Utils
import java.io.BufferedInputStream
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileOutputStream
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.TimeZone
import java.util.regex.Pattern
import java.util.zip.ZipInputStream


/**
 * @Author Xing
 * @CreateTime 2025年09月24日
 * @Description TODO
 */
object PublicUtils {

    fun isEmail(str:String?):Boolean{
        if(str.isNullOrEmpty()) return false
        val emailPattern = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$"
        return Pattern.matches(emailPattern, str)
    }

    fun getAppVersionName(context: Context): String {
        try {
            val pm: PackageManager = context.packageManager
            val pi = pm.getPackageInfo(context.packageName, 0)
            return if (pi == null) "" else "${pi.versionName}"
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
            return ""
        }
    }

    fun getAppVersionCode(context: Context): Int {
        try {
            val pm: PackageManager = context.packageManager
            val pi = pm.getPackageInfo(context.packageName, 0)
            return pi?.versionCode ?: -1
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
            return -1
        }
    }

    /**
     * 将毫秒级时间戳格式化为日期字符串
     * @param timestampMs 毫秒时间戳（epoch millis）
     * @param pattern 日期格式，默认 yyyy-MM-dd HH:mm:ss
     * @param timeZone 时区，默认设备当前时区
     * @param locale 语言区域，默认设备当前区域
     */
    fun formatTimestampMs(
        timestampMs: Long,
        pattern: String = "yyyy-MM-dd HH:mm:ss",
        timeZone: TimeZone = TimeZone.getDefault(),
        locale: Locale = Locale.getDefault()
    ): String {
        return try {
            val sdf = SimpleDateFormat(pattern, locale).apply { this.timeZone = timeZone }
            sdf.format(Date(timestampMs))
        } catch (e: Exception) {
            ""
        }
    }

    /**
     * 将秒级时间戳格式化为日期字符串（内部转换为毫秒）
     * @param timestampSeconds 秒时间戳（epoch seconds）
     * @param pattern 日期格式，默认 yyyy-MM-dd HH:mm:ss
     * @param timeZone 时区，默认设备当前时区
     * @param locale 语言区域，默认设备当前区域
     */
    fun formatTimestampSeconds(
        timestampSeconds: Long,
        pattern: String = "yyyy-MM-dd HH:mm:ss",
        timeZone: TimeZone = TimeZone.getDefault(),
        locale: Locale = Locale.getDefault()
    ): String = formatTimestampMs(timestampSeconds * 1000, pattern, timeZone, locale)

    /**
     * 根据国家/地区编码返回对应的中文名称（大小写不敏感）。
     * 支持常见 Alpha-2（如 US、HK）和部分 Alpha-3（如 USA、HKG）别名。
     * 若无法识别，直接返回编码。
     */
    fun countryNameZh(code: String?): String {
        if (code.isNullOrBlank()) return ""
        val norm = code.trim().uppercase(Locale.ROOT)
        val alpha3To2 = mapOf(
            "USA" to "US", "HKG" to "HK", "CHN" to "CN", "TWN" to "TW", "MAC" to "MO",
            "GBR" to "GB", "JPN" to "JP", "KOR" to "KR", "DEU" to "DE", "FRA" to "FR",
            "ITA" to "IT", "ESP" to "ES", "RUS" to "RU", "CAN" to "CA", "AUS" to "AU",
            "IND" to "IN", "BRA" to "BR", "ZAF" to "ZA", "MEX" to "MX", "NLD" to "NL",
            "SWE" to "SE", "NOR" to "NO", "DNK" to "DK", "FIN" to "FI", "CHE" to "CH",
            "AUT" to "AT", "BEL" to "BE", "IRL" to "IE", "NZL" to "NZ", "SGP" to "SG",
            "MYS" to "MY", "THA" to "TH", "VNM" to "VN", "PHL" to "PH", "IDN" to "ID",
            "PAK" to "PK", "TUR" to "TR", "SAU" to "SA", "ARE" to "AE", "ISR" to "IL",
            "EGY" to "EG", "NGA" to "NG", "ARG" to "AR", "CHL" to "CL", "COL" to "CO",
            "PER" to "PE", "POL" to "PL", "CZE" to "CZ", "HUN" to "HU", "GRC" to "GR",
            "PRT" to "PT", "ROU" to "RO", "BGR" to "BG", "UKR" to "UA"
        )
        var iso2 = when {
            norm.length == 3 -> alpha3To2[norm] ?: norm
            else -> norm
        }
        if (iso2 == "UK") iso2 = "GB"
        // 使用 Locale 以简体中文获取显示名称
        val display = Locale("", iso2).getDisplayCountry(Locale.SIMPLIFIED_CHINESE)

        //若有想自定义名称
        val override = when (iso2) {
            "HK" -> "香港"
            "MO" -> "澳门"
            else -> null
        }
        val name = override ?: display
        return if (name.isNullOrBlank()) "$code" else name
    }

}